﻿using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;

namespace MVBuddy.Common.Helpers
{
    public static class StorageManager
    {
        public static void SaveAppSetting(string settingName, object value)
        {
            IsolatedStorageSettings.ApplicationSettings[settingName] = value;
            IsolatedStorageSettings.ApplicationSettings.Save();
        }

        public static T LoadAppSetting<T>(string settingName)
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains(settingName))
            {
                return (T)IsolatedStorageSettings.ApplicationSettings[settingName];
            }

            return default(T);
        }

        public static void ClearAppSettings()
        {
            IsolatedStorageSettings.ApplicationSettings.Clear();
            IsolatedStorageSettings.ApplicationSettings.Save();
        }

        public static void SaveShellBitmapAsJpeg(string filename, WriteableBitmap bitmap)
        {
            IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForApplication();

            string directoryPath = Path.GetDirectoryName(filename);
            if (!userStore.DirectoryExists(directoryPath))
            {
                userStore.CreateDirectory(directoryPath);
            }

            using (var stream = userStore.OpenFile(filename, FileMode.OpenOrCreate))
            {
                bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
            }
        }
    }
}
